import queue
import json
import config
from act.qwen import call_qwen_model
from dataDeal.dictUtils import deal_inquiry_summary_dict
from dataDeal.fileUtils import save_to_json, save_resolve_result


# 解析银行报价，同时持久化
def parse_bank_offer_and_save(inquiry_question: str, last_msg: str, name: str, time_shot: str):
    input_str = config.nowtime_str + '\n\n' + inquiry_question + '\n\n' + last_msg
    result = call_qwen_model(config.prompt_resolve_bank, input_str)
    if result[0]:
        print(f'{name}存款行报价大模型解析结果:{result[1]}')
        data_dict = {}
        try:
            data_dict = json.loads(result[1])
        except Exception as e:
            print(f"存款行回价利率解析失败，大模型解析结果有误！具体异常：{e}")
        # 遍历data_dict并追加
        deal_inquiry_summary_dict(config.inquiry_summary_dict[name], data_dict, time_shot)
        save_to_json(config.inquiry_summary_dict[name], config.bank_ratio_path_dict[name])
        # 保存对应聊天记录
        config.chat_history_dict[name][time_shot] = inquiry_question + '\n\n' + last_msg
        save_to_json(config.chat_history_dict[name],
                     config.chat_history_path_dict[name])


def parse_ratio_and_save(inquiry_question: str, last_msg: str, name: str):
    input_str = name + '\n\n' + inquiry_question + '\n\n' + last_msg
    result = call_qwen_model(config.prompt_resolve_rate, input_str)
    if result[0]:
        print(f'{name}的[利率询价]大模型解析结果:{result[1]}')
        data_dict = {}
        try:
            data_dict = json.loads(result[1])
        except Exception as e:
            print(f"利率解析失败，大模型解析结果有误！具体异常：{e}")
        save_resolve_result(data_dict, config.resolve_result_path, name, config.name_include,
                            config.status_dict, config.status_dict_file_path)


def parse_and_save(q):
    while True:
        data = q.get()
        if data is None:
            print('子线程处理完毕，子线程退出')
            break
        parse_bank_offer_and_save(data.inquiry_question, data.last_msg, data.bank_name, data.time_shot)
        parse_ratio_and_save(data.inquiry_question, data.last_msg, data.bank_name)
        q.task_done()
